package com.ksyun.campus.client;

import com.alibaba.fastjson.JSONObject;
import com.ksyun.campus.client.util.HttpClientConfig;
import com.ksyun.campus.client.util.HttpClientUtil;
import org.apache.hc.client5.http.HttpResponseException;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.jboss.netty.handler.codec.http.HttpMethod;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public abstract class FileSystem {
    private String fileSystem;
    private static HttpClient httpClient;

    public FileSystem(){
    }
    public FileSystem(String fileSystem) {
        this.fileSystem = fileSystem;
    }

    protected CloseableHttpResponse callRemote(String targetUrl, Map<String, ?> header, HttpMethod method){
//        httpClient.execute();
        // 创建 HttpClient
        httpClient = HttpClientUtil.createHttpClient(new HttpClientConfig());

        ClassicHttpRequest request = null;
        if (method.equals(HttpMethod.GET)) {
            request = new HttpGet(targetUrl);
            //设置头部
            addHeaders(request, header);
        } else if (method.equals(HttpMethod.POST)) {
            request = new HttpPost(targetUrl);
            // Set headers if provided
            addHeaders(request,header);
        } else if (method.equals(HttpMethod.DELETE)) {
            request = new HttpDelete(targetUrl);
        } else {
            throw new RuntimeException("请求方法不能为空!");
        }

        try {
            // 执行请求
            CloseableHttpResponse response = (CloseableHttpResponse)httpClient.execute(request);

            // 处理响应，例如读取响应内容
            return response;
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置请求头
     * @param request
     * @param headers
     */
    private void addHeaders(HttpRequest request, Map<String, ?> headers) {
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, ?> entry : headers.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    protected CloseableHttpResponse callRemoteAddFile(String targetUrl, Map<String, ?> header, byte[] data){
        httpClient = HttpClientUtil.createHttpClient(new HttpClientConfig());
        HttpPost httpPost = new HttpPost(targetUrl);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        String filename = (String) header.get("path");
        builder.addBinaryBody("file", data, ContentType.MULTIPART_FORM_DATA, filename);
        // 如果需要，传递额外参数
        // StringBody fileName = new StringBody("文件名称", ContentType.MULTIPART_FORM_DATA);
        // StringBody userName = new StringBody("用户名", ContentType.MULTIPART_FORM_DATA);
        // builder.addPart("fileName", fileName);
        // builder.addPart("userName", userName);

        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = (CloseableHttpResponse) httpClient.execute(httpPost);
            return response;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected <T> T handleResponse(CloseableHttpResponse response, Class<T> responseType) {
        if (response.getCode() != HttpStatus.SC_OK) {
            try {
                throw new HttpResponseException(response.getCode(), "HTTP request failed");
            } catch (HttpResponseException e) {
                throw new RuntimeException(e);
            }
        }
        HttpEntity entity = response.getEntity();
        String responseBody = null;
        try {
            responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            return  (T) JSONObject.parseObject(responseBody, responseType);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
